<template>
  <div class="character">
    <el-form :inline="true" :model="searchParams" label-position="left">
      <el-form-item>
        <el-button type="primary" @click="handleAdd">添加角色</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      :title="editData.id?'编辑':'添加'"
			:visible.sync="dialogVisible"
      width="500px">
      <el-form v-loading="isLoadEditData" ref="ruleForm" :model="editData" label-width="100px" class="demo-ruleForm">
        <el-form-item v-if="editData.id" label="id" prop="id">
					<el-input v-model="editData.id"></el-input>
				</el-form-item>
				<el-form-item label="角色名称" prop="title">
					<el-input v-model="editData.title"></el-input>
				</el-form-item>				
				<el-form-item label="备注" prop="remark">
					<el-input type="textarea" v-model="editData.remark"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="editSave">确 定</el-button>
			</span>
    </el-dialog>
    <el-dialog
      title="角色授权"
			:visible.sync="dialogVisible1"
      width="500px">
      <el-form v-loading="isLoadEditData" ref="ruleForm" :model="warrantData" label-width="100px" class="demo-ruleForm">
        <el-form-item label="id" prop="id">
					<el-input v-model="warrantData.id"></el-input>
				</el-form-item>
				<el-form-item label="授权的节点id" prop="node_id">
					<el-scrollbar style="height: 500px;">
            <el-tree              
              :data="nodes"
              ref="tree"
              show-checkbox
              auto-expand-parent
              node-key="id"
              default-expand-all
              :props="defaultProps"
              :default-checked-keys="defaultCheKey"
            >
            </el-tree>
          </el-scrollbar>
				</el-form-item>				
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="editCommit">确 定</el-button>
			</span>
    </el-dialog>
    <el-table 
      :data="dataList" 
      v-loading = "loading"
      style="margin-top: 12px"
      border>
      <el-table-column
        prop="id"
        label="id"
        min-width="60px"
        align="center">
      </el-table-column>
      <el-table-column
        prop="title"
        label="角色"
        min-width="120px"
        align="center">         
      </el-table-column>
      <el-table-column
        prop="status"
        label="角色状态"
        min-width="120px"
        align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#5FB878"
            inactive-color="#ccc"
            :active-value= "1"
            :inactive-value="0"
            :active-text="scope.row.status == 1?'启用':'　禁用'"
            :width="45"
            @change="changeStatus($event,scope.row.id)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        min-width="120px"
        align="center">        
      </el-table-column>
      <el-table-column
        prop="create_at"
        label="创建时间"
        min-width="135px"
        align="center">        
      </el-table-column>
      <el-table-column prop="" label="操作" align="center" min-width="220px">
				<template slot-scope="scope">
          <el-button
            size="mini"
						type="success"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
					<el-button
						size="mini"
						type="danger"
            @click="handleDelete(scope.row)"
						>删除</el-button>
          <el-button
						size="mini"
						type="success"
            @click="handleAuthorize(scope.row)"
						>角色授权</el-button>
				</template>
			</el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 12px;"
        @size-change="pageSizeChange"
        :current-page="page_info.page"
        :page-size="page_info.limit"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        layout="prev, pager, next, jumper, sizes"
        :page-count="page_info.total_page"
      >
    </el-pagination>
  </div>
</template>
<script>
export default {
  name: 'character',
  data () {
    return {
      dataList: [],  //角色列表数据
      loading: false,  //加载
      isLoadEditData: false,  //弹框数据加载
      searchParams: {},  //搜索栏数据
      dialogVisible: false,  //编辑，添加弹框,
      dialogVisible1: false,
      editData: {  //编辑，添加弹框数据
        id: null,
        title: '',
        remark: ''
      },
      warrantData: {  //授权弹框数据
        id: '',
        node_id: []
      },
      nodes: [], //所有节点数据
      defaultProps: {
        children: 'sub',
        label: 'title'
      },
      defaultCheKey: [],
      page_info: {
        limit: 10,  //每页显示条数
        page: 1,   //当前页
        total_page: null   //总共页数          
      },
    }
  },
  methods: {
    /**
     * 获取列表
     */
    getList(page = 1){
      this.loading = true;
      this.$http.get('/auth/list',{page, limit: this.page_info.limit}).then(res => {
        if(res.status === 200){          
          this.dataList = res.data.result.data;
          this.loading = false;
        }
      })
    },
    /**
     * 角色权限状态
     */
    changeStatus(status,num){
      this.$http.post('/auth/status',{
        id: num,
        status: status
      }).then( res => {
        this.$message({
          message: res.data.result.msg,
          center: true,
          type: 'success',
          offset:400,
          duration:1000
        });
      })
    },

    /**
     * 增加角色
     */
    handleAdd(){
      this.dialogVisible = true;
      this.editData.id = null;
      this.editData.title = '';
      this.editData.remark = '';
    },
    /**
     * 编辑角色
     */
    handleEdit (row) {
      this.dialogVisible = true;
      this.isLoadEditData = true;
      this.editData.id = row.id;
      this.editData.title = row.title;
      this.editData.remark = row.remark;
      this.isLoadEditData = false;
    },
    editSave () {
      let actionUrl = this.editData.id ? '/auth/edit' : '/auth/add';
			this.$http.post(actionUrl, this.editData).then(res=>{
        if (res.status === 200) {
          this.getList();
          this.dialogVisible = false;
        }
      });
    },
    /**
     * 删除角色
     */
    handleDelete (row) {
      this.$confirm('此操作将删除title='+ row.title +'这个角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post("/auth/del", {
          id: row.id
        }).then( res => {
          this.getList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '已取消删除'
        });          
      });
    },

    /**
     * 角色授权
     */
    handleAuthorize(row){
      // console.log(row)
      this.dialogVisible1 = true;
      this.isLoadEditData = true;
      this.warrantData.id = row.id;
      if(row.node_id){
        let arrD = JSON.parse(row.node_id)
        arrD.forEach(key => {
          this.$refs['tree'].setChecked(Number(key), true)
        })
      }      
      this.isLoadEditData = false;
    },
    editCommit () {
      let val = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());    
      this.$http.post('/auth/apply',{
        id: this.warrantData.id,
        node_id: JSON.stringify(val)
      }).then(res => {
        if(res.status === 200){
          this.$message({
            type: 'success',
            message: '授权成功!'
          })
          this.warrantData.id = null;
          this.$refs.tree.setCheckedKeys([]); //取消所有的选择
          this.dialogVisible1 = false;
        }
      })
    },
    // 格式转换
    changeData (arr) {
      arr.forEach(item => {
        let obj = []
        if(typeof (item.sub) === 'object'){
          for(let i in item.sub){
            obj.push(item.sub[i])
          }
          item.sub = obj          
          this.changeData(item.sub)
        }
      })
      return arr;
    },
    /**
     * 改变每页页数
     */
    pageSizeChange (pageSize) {
      this.page_info.limit = Number(pageSize);
			this.getList();
    },
  },
  created () {
    let arr = [];
    this.$http.post('/node/index').then(res => {
      if(res.status === 200) {        
        arr = res.data.result;
        this.nodes = this.changeData(arr)
        // console.log(this.nodes)
      }
    })
  },
  mounted () {
    this.getList();
  }
}
</script>
<style lang="less" scoped>
  
</style>